<?php

namespace common\jobs\handle;

use Yii;
use yii\base\Exception;
use common\helpers\ArrayHelper;
use common\models\shop\ShopGoods;

/**
 * 商城订单队列操作
 *
 */
class OfcSeasonHandle extends \common\models\shop\ShopOrder {

    /**
     * 取消过期订单
     * @param type $id
     * @param type $msg
     * @return boolean
     */
    public static function cancelExpired($id, &$msg) {
        try {
            $model = static::findOrFail($id);
        } catch (Exception $e) {
            $msg = $e->getMessage();
            return false;
        }
        if (!$model->canCancel || !$model->isExpired) {
            $msg = '订单状态不符合取消标准';
            return false;
        }
        $model->status = static::STATUS_CANCEL;
        //回收库存
        $stocks = ArrayHelper::map($model->goods, 'goods_id', 'goods_number');

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception('交易创建失败！' . ArrayHelper::toString($order->errors));
            }
            foreach ($model->goods as $sku) {
                $goods = ShopGoods::findOne($sku->goods_id);
                if (!$goods) {
                    continue;
                }
                $goods->stock += $sku->goods_number;
                if (!$goods->save()) {
                    throw new Exception($goods->getErrorMsg());
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $msg = $e->getMessage();
            return false;
        }

        return true;
    }

}
